package com.ai.sml.action;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;

import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.ai.sml.util.CacheUtil;
import com.ai.sml.util.ValidateCodeUtil;

/**
 * Servlet implementation class Test
 */
public class QueryValidateCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getActionLog(QueryValidateCodeServlet.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public QueryValidateCodeServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 设置响应头 Content-type类型
		response.setContentType("image/jpeg");
		// 以下三句是用于设置页面不缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setDateHeader("Expires", 0);
		if(request.getSession().getAttribute("userId")==null){
			SecurityUtils.getSubject().logout(); 
		}
		OutputStream os = response.getOutputStream();
		Map map=ValidateCodeUtil.getValidateCodeImg();
		String code=(String) map.get("code");
		BufferedImage image=(BufferedImage) map.get("image");
		// 将验证码记录到session
//		request.getSession().setAttribute("validateCode", code);
		String cacheImgKey = request.getParameter("cacheImgKey");
		CacheUtil.put2Cache(cacheImgKey, code, 60);
		logger.info("cacheImgKey = ", cacheImgKey);
		logger.info("code = ", code);
	/*	ApplicationContext context = new ClassPathXmlApplicationContext(
				"spring/spring-services.xml");
		ICacheService cacheService = (ICacheService)context.getBean("cacheService");
		try {
			cacheService.put2Cache("validateCode", code,300);
			System.out.println("cacheService==============>validateCode:"+cacheService.getStrFromCache("validateCode"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	*/	
		
		// 输出图像到页面
		ImageIO.write(image, "JPEG", os);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
